package com.ruoyi.project.sms.qcloud;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.ruoyi.common.constant.SystemContstant;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.content.PropertyTypeEnum;
import com.ruoyi.project.sms.ISMSService;
import com.ruoyi.project.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service (value = "qcloud")
public class QCloudSmsServiceImpl implements ISMSService {

    // 短信应用 SDK AppID
    @Value ("${sms.qcloud.appid}")
    private int APP_ID; // SDK AppID 以1400开头

    // 短信应用 SDK AppKey
    @Value ("${sms.qcloud.appkey}")
    private String APP_KEY;

    @Value ("${sms.qcloud.smsSign}")
    private String smsSign;

    @Value ("${sms.qcloud.templateId}")
    private int templateId; // NOTE: 这里的模板 ID`7839`只是示例，真实的模板 ID 需要在短信控制台中申请

    @Autowired
    private RedisUtils redisUtils;

    public static final String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMAL04mTnVnpja84CEWe1Ztbh6vqOwJyKfm6LxjoOz6zzP8ZMY9v25naKus8aShIm90GtnnOl9dse4fXSzGgHe5yYvgd1FWO9LmYe1bHVuQq4kbRg69QjZivUI+lP9Cf2Y0hzJvf9eMQUJ3iYhVCUcS+TRaF9H/jQ2DpOluiqfIHAgMBAAECgYBYmhwycOQ7w0EXAebvF+S9FHF3o00uR7WN/ZQVDa+nshR17Q2se5L5XGpItUpex4EBbENr1yC+xtIHThDnCFRGDTw6B0YJ9hF4vHnMrVWluLps5xMHUdDQPC4n9hshJzjHWCTitoloFRcjtTh3rU2OZdJS9Cbb/BZjtSbYuO14wQJBAPDZP0c+T5G8GTHBwY4mpP+YRB9nG2hzXEmQWPHW7q+GKZcyGltONwG1FJM83Q6fjCE6slx6hNUc5/7+QflI718CQQDMIKOkSwgWhkskSlqswa3kz5FdRo1uUOE4JU4ibuIfP7lri66Q6e1u1H5mpcVPdOQE74B0K+qSLWIGW0aa3YZZAkAI/TK9Z/f0Sn7uOnsM4ShbWcWBHooJVfTl0ftf21PBPVKkD/yn17151NZVwHnHp/DE9LnfdbsrcQ6/l6HCuhQlAkEAhtKQAvWj0+zDOKb7mNsbleMa6fatd01oVAMfxlJie61FNKk/lWtMbUVgbz/SQJa9/ByMRS60cfQTqIsk6SijkQJAIAL++05CiLqDQVYUFDeVrjSSWvKnBj3eMvf9jcylCVHSfKu/OeCfEb5QDdEAbyCDKr2QgcbEEmeqATniqUbruw==";

    public static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAC9OJk51Z6Y2vOAhFntWbW4er6jsCcin5ui8Y6Ds+s8z/GTGPb9uZ2irrPGkoSJvdBrZ5zpfXbHuH10sxoB3ucmL4HdRVjvS5mHtWx1bkKuJG0YOvUI2Yr1CPpT/Qn9mNIcyb3/XjEFCd4mIVQlHEvk0WhfR/40Ng6TpboqnyBwIDAQAB";


    @Override
    public String sendCode (String mobile, Integer length) throws Exception {
        RSA rsa = new RSA(PRIVATE_KEY, PUBLIC_KEY);
        try {
            mobile = rsa.decryptStr(mobile, KeyType.PrivateKey);
        } catch (Exception e) {
            throw new RuntimeException("手机解密失败");
        }
        if (StringUtils.isBlank(mobile) || mobile.length() != 11) {
            throw new RuntimeException("手机号码错误");
        }

        String randomCode = this.getRandomCode(length == null || length.intValue() == 0 ? 4 : length);
        SmsSingleSenderResult results = null;
        Map <String, Object> resultmap = new HashMap <>();
        SmsSingleSender ssender = new SmsSingleSender(this.APP_ID, this.APP_KEY);
        results = ssender.sendWithParam("86", mobile, Integer.valueOf(this.templateId), new String[] {randomCode},
                this.smsSign, "", ""
        );
        if (results != null && results.result != 0) {
            throw new RuntimeException("短信发送失败，原因:" + results.errMsg);
        }
        this.redisUtils.set(SystemContstant.CHECK_CODE + mobile, randomCode);
        this.redisUtils.expire(SystemContstant.CHECK_CODE + mobile, 120);
        //return results.errMsg;
        return "发送成功";
    }

    @Override
    public String sendGroupMsg (String[] mobiles, String[] msg) throws Exception {
        return "失败";
    }

    /**
     * 校验手机验证码 验证码错误时返回true
     *
     * @param mobile
     * @param checkCode
     *
     * @return
     */
    @Override
    public boolean checkSmsCode (String mobile, String checkCode) {
        String sysCheckCode = this.redisUtils.hget(PropertyTypeEnum.SYS.getText(), "sys_check_code")+"";
        if (sysCheckCode.equals(checkCode)) {
            this.redisUtils.del(SystemContstant.CHECK_CODE + mobile);
            return false;
        }
        //通过缓存获取手机验证码
        String code = this.redisUtils.get(SystemContstant.CHECK_CODE + mobile);
        if (StringUtils.isEmpty(code)) {
            return true;
        }
        //不相等时返回错误
        if (!code.equals(checkCode)) {
            return true;
        }
        this.redisUtils.del(SystemContstant.CHECK_CODE + mobile);
        return false;
    }

    /**
     * 获取随机验证码
     *
     * @param length
     *
     * @return
     */
    @Override
    public String getRandomCode (int length) {
        StringBuffer code = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    @Override
    public String sendYaoqing (String mobile, String username) throws Exception {

        SmsSingleSenderResult results = null;
        SmsSingleSender ssender = new SmsSingleSender(this.APP_ID, this.APP_KEY);
        results = ssender.sendWithParam("86", mobile, Integer.valueOf(923205), new String[] {username}, this.smsSign,
                "", ""
        );
        if (results != null && results.result != 0) {
            //     throw  new Exception("短信发送失败，原因:" + results.errMsg);
        }
        //  System.out.println(username);
        //return results.errMsg;
        return "发送成功";
    }

    @Override
    public String decrypt (String str) throws Exception {
        return null;
    }

    @Override
    public String sendservice (String mobile, String TemplateCode) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getMobile (String mobile) throws Exception {
        return null;
    }

    @Override
    public void sendMarketingMsg (List <String> phones, String template) {

    }

    @Override
    public void sendMsgByCode(String mobile, String code) throws Exception {

    }

    @Override
    public Boolean sendMsgByCodeResult(String mobile, String code) throws Exception {
        return null;
    }

    @Override
    public void sendMsgByParameters(String mobile, String code, String templateParam) throws Exception {
        
    }
}
